package com.shd.edanpei.map;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.shd.edanpei.base.MyApplication;

/**
 * Created by mc on 2018/8/13.
 * yang-wen-wen
 */

public class MapManger {

    private static AMapLocationClient getMapClient() {
        return LocaitonHolder.AMAP_LOCATION_CLIENT;
    }

    private static class LocaitonHolder {
        private static final AMapLocationClient AMAP_LOCATION_CLIENT = new AMapLocationClient(MyApplication.getApplication());
        private static final AMapLocationClientOption A_MAP_LOCATION_CLIENT_OPTION = new AMapLocationClientOption()
                .setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn)
                .setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
                .setOnceLocation(true)
                .setNeedAddress(true);
    }

    public static void getLocation(final MapLocationListener listener) {
        getMapClient().setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析aMapLocation获取相应内容。
                        listener.onLocationSuccess(aMapLocation);
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        String error = "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo();
                        listener.onLocationFail(error);
                    }
                }
            }
        });
        getMapClient().setLocationOption(LocaitonHolder.A_MAP_LOCATION_CLIENT_OPTION);
        getMapClient().startLocation();
    }


    public interface MapLocationListener {

        void onLocationSuccess(AMapLocation aMapLocation);

        void onLocationFail(String error);
    }
}
